﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Blackbird.Core.Editable.Frames;

namespace Blackbird.Studio.ViewModel.EntityViewModels
{
    public class EditableFramesetPreviewViewModel : EntityViewModel<EditableFrameset>, IRenderable
    {
        private DateTime _lastRendertime;
        private bool _rendererInitialized;
        private Rect _imageRect;
        private int _framesetIndex;
        private int _framesetLength;
        private double _msPerFrame;

        public EditableFramesetPreviewViewModel(EditableFrameset model) : base(model)
        {
            _lastRendertime = DateTime.Now;
        }

        public override EntityType EntityType
        {
            get { return EntityType.Frameset; }
        }

        public BitmapSource CurrentFrame { get; private set; }



        public void InitializeRenderer() {
            if (!_rendererInitialized) {
                _imageRect = new Rect(0, 0, Model[0].Width, Model[0].Height);
                _framesetIndex = 0;
                _framesetLength = Model.Count();
                _msPerFrame = (1.0 / Model.Fps) * 1000.0;
                _rendererInitialized = true;
            }
        }

        public void DeinitializeRenderer()
        {
            _rendererInitialized = false;
        }

        public void Render()
        {
            var renderTime = DateTime.Now;
            var deltaMilliSeconds = (renderTime - _lastRendertime).TotalMilliseconds;

            if ((deltaMilliSeconds >= _msPerFrame) && Model.Any()) {
                _framesetIndex++;
                if (_framesetIndex > _framesetLength - 1) _framesetIndex = 0;
                var visual = new DrawingVisual();
                using (var context = visual.RenderOpen()) {
                    context.DrawImage(Model[_framesetIndex].BitmapSource, _imageRect);
                }
                
                _lastRendertime = renderTime;
            }
        }
        
    }
}
